using System;
using System.Collections.ObjectModel;
using System.IO;
using EnvDTE;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.VisualStudio.Shell;

namespace IncrementalSave
{
    public class FileHistoryViewModel
    {
        private ObservableCollection<HistoryItem> _historyItems = new ObservableCollection<HistoryItem>();

        private FileHistoryTracker _tracker;

        public DelegateCommand<HistoryItem> OpenViewCommand { get; set; }

        private HistoryItem _selectedHistoryItem;
        public HistoryItem SelectedHistoryItem
        {
            get { return _selectedHistoryItem; }
            set
            {
                if (_selectedHistoryItem == value)
                    return;
                _selectedHistoryItem = value;
                _tracker.OpenView(_selectedHistoryItem);
            }
        }

        public FileHistoryViewModel()
        {
            OpenViewCommand = new DelegateCommand<HistoryItem>(OpenViewCommandExecuted);
        }

        private void OpenViewCommandExecuted(HistoryItem historyItem)
        {
            _tracker.OpenView(historyItem);
        }

        private void HistoryItemsChanged(object sender, EventArgs e)
        {
            HistoryItems.Clear();
            foreach (var historyItem in _tracker.HistoryItems)
            {
                HistoryItems.Add(historyItem);
            }
        }


        public ObservableCollection<HistoryItem> HistoryItems
        {
            get
            {
                return _historyItems;
            }
        }

        private IncrementalSavePackage _package;
        public IncrementalSavePackage Package
        {
            get { return _package; }
            set
            {
                _package = value;
                if (_tracker != null)
                    _tracker.HistoryItemsChanged -= HistoryItemsChanged;
                _tracker = _package.HistoryTracker;
                foreach (var historyItem in _tracker.HistoryItems)
                {
                    HistoryItems.Add(historyItem);
                }
                _tracker.HistoryItemsChanged += HistoryItemsChanged;
            }
        }

        //private void HistoryItemAdded(object sender, FileHistoryTracker.HistoryItemsChangedEventArgs e)
        //{
        //    HistoryItems.Add(e.HistoryItem);
        //}
    }
}